import fetch from 'isomorphic-fetch'
import router from 'router/index'

/**
 * [根据简写匹配域名]
 * @param  {[Stiring]} abbr [简写名称]
 * @return {[Stiring]}      [域名]
 */
function matchDomain(abbr) {
  const isProduction = process.env.NODE_ENV === 'production'

  switch (abbr.toLowerCase()) {
    case 'tool':
      return isProduction ? 'http://tool.in.juanpi.com/' : '/tool/'

    case 'mapi':
      return isProduction ? 'http://mapi.in.juanpi.com/' : '/mapi/'

    default:
      return 'http://mapi.juanpi.in/'
  }
}

/**
 * 把对象序列化成url参数形式
 * @param  {[Object]} obj [需要序列化的对象]
 * @return {[String]}     [{a:1,b:2} ==> ?a=1&b=2]
 */
function serialiseObject(obj) {
  /* eslint-disable prefer-template */
  if (obj && Object.keys(obj).length) {
    return '?' + Object.keys(obj).map(key =>
      key + '=' + encodeURIComponent(obj[key]),
    ).join('&')
  }
  return ''
}

function getUrl(path, params) {
  if (path.startsWith('http')) {
    return path + serialiseObject(params)
  }

  const ret = path.split('@')
  const isProduction = process.env.NODE_ENV === 'production'
  const defaultDomain = isProduction ? 'http://mapi.juanpi.in/' : '/api/'

  // 如果path中包含@符号
  if (ret.length === 2) {
    const domain = matchDomain(ret[0])
    return domain + ret[1] + serialiseObject(params)
  }

  return defaultDomain + ret[0] + serialiseObject(params)
}

function getBaseConfig() {
  const userInfo = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {}
  const headers = {
    jpPlatform: 'M',
    jpAppCountry: 'IN',
    jpSign: userInfo.userToken,
    jpUid: userInfo.userId,
  }
  const config = {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      ...headers,
    },
  }
  return config
}

function checkStatus(res) {
  if (res.code === 902) {
    // 需要重新登录 先登出 然后在跳转到登录页面
    delete sessionStorage.userInfo
    sessionStorage.redirect = router.currentRoute.fullPath
    router.push({ path: './login' })
    throw new Error(res.info)
  }
  return res
}

function jsonParse(res) {
  return res.json()
}

const http = {
  get: (function get() {
    const cache = {}
    const initConfig = {
      cacheable: false,
      maxAge: 60,
    }

    /**
     * [getThemeInfoBody description] get请求缓存配置
     * @param  {Bool} config.cacheable [是否开启缓存]
     * @param  {Number} config.maxAge [缓存时间(单位: s)]
     */
    return (path, params, config) => {
      config = config || initConfig
      const url = getUrl(path, params)
      const fetchData = () => new Promise((resolve, reject) => {
        fetch(url, getBaseConfig())
          .then(jsonParse)
          .then(checkStatus)
          .then(res => resolve(res))
          .catch(err => reject(err))
      })
      const isExpire = (newTime, oldTime, maxAge) => {
        // maxAge等于0，一直缓存
        if (maxAge === 0) return false
        return newTime - oldTime >= maxAge * 1000
      }

      if (config.cacheable) {
        const oldVal = cache[url]
          // 如果cache有值且未过期
        if (oldVal && !isExpire(Date.now(), oldVal.timeAt, config.maxAge)) {
          cache[url] = oldVal
        } else {
          cache[url] = {
            value: fetchData(),
            timeAt: Date.now(),
          }
        }
        return cache[url].value
      }
      return fetchData()
    }
  }()),

  post(path, payload) {
    return new Promise((resolve, reject) => {
      fetch(getUrl(path), {
        ...getBaseConfig(),
        method: 'POST',
        body: JSON.stringify(payload),
      })
        .then(jsonParse)
        .then(checkStatus)
        .then(res => resolve(res))
        .catch(err => reject(err))
    })
  },

}

export default http
